package com.example.demo5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 张成
 * @date 2022/3/22 10:39
 * @version 1.0
 */
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");

        //判断 是否已经登录
        if (username == null || username.isEmpty()) {
            //获取 cookies
            Cookie[] cookies = request.getCookies();
            // 遍历cookies数组
            String lastAccessTime = null;
            for (int i = 0; cookies != null && i < cookies.length; i++) {
                if ("lastAccess".equals(cookies[i].getName())) {
                    // 如果cookie的名称为lastAccess,则获取该cookie的值
                    lastAccessTime = cookies[i].getValue();
                }
            }
            //已经登录
            if (lastAccessTime != null) {
                response.sendRedirect("WelcomeServlet");
            } else {
                response.sendRedirect("login.html");
            }
        }

        String password = request.getParameter("password");
        PrintWriter pw = response.getWriter();

        //判断登录表单
        if (("zc").equals(username) && ("123").equals(password)) {
            // 创建cookie,将当前时间作为cookie的值发送给客户端
            Cookie cookie = new Cookie("lastAccess", username);
            cookie.setMaxAge(60 * 60); //设置cookie最大存在时间
            // 发送 cookie
            response.addCookie(cookie);
            response.sendRedirect("WelcomeServlet");
        } else {
            pw.write("用户名或密码错误，登录失败");
        }

    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
